package com.zy.explore.aspect;

import com.alibaba.fastjson.JSON;
import com.zy.explore.annotation.DeSensitiveMethod;
import com.zy.explore.config.ConstantProperties;
import com.zy.explore.util.DesensitizedUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;

/**
 * description 脱敏切面
 *
 * 使用方法：com.zy.explore.controller包
 * 中类方法返回的对象(或包装的基类)增加@DeSensitiveField(type=SensitiveTypeEnum.ENCRYPT)注解
 * 且该方法增加@DeSensitiveMethod注解标注，Facade方法返回之前会被此切面拦截进行相应字段的脱敏操作
 *
 * @author ZY
 * @date 2021年05月11日 11:36
 */
@Component
@Aspect
@Slf4j
public class DeSensitiveAspect {

    @Resource
    private ConstantProperties constantProperties;

    @Pointcut("execution(* com.zy.explore.controller.*..*(..))")
    public void deSensitive() {
    }

    /**
     * 统计方法执行时间
     *
     * @author ZY
     * @date 2021年05月11日 11:36
     */
    @Around("deSensitive()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        // result 为方法的返回值
        Object result = pjp.proceed();

        if (result == null) {
            return null;
        }
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        DeSensitiveMethod annotation = method.getAnnotation(DeSensitiveMethod.class);
        if (annotation != null) {
            String json = DesensitizedUtil.getJson(result, constantProperties.getAesKey());
            Class<?> clazz = result.getClass();
            return JSON.parseObject(json, clazz);
        }
        return result;
    }
}
